$(function() {

	//订单取消类型
    sys.selectpicker({
        id : 'cancelReasonCombo', // select的id
        url : rootPath + "/dict/listKeyMapEntites", // 请求数据的远程地址
        param : {
            keyType : 'orderCancelReason'
        }, // 过滤参数
        // defaultValue:{},
        valueField : 'keyValue',
        textField : 'keyIntro'
    });
    
    $("#cancelReasonCombo").on("change", function() {
        $("#cancelReason").val($("#cancelReasonCombo option:selected").text());
    });
    
	// 定义列
	var columns = [
		{
				field : 'no',
				title : '序号',
				align : 'left',
				formatter : function(value, row, index) {
					return index + 1;
				},
				width:"5%"
		},
		{
			field : 'imagePath',
			title : '商品图片',
			align : 'center',
			formatter : function(value, row, index) {
				return "<div class='order_detail_product_image'>"+
				        	"<a rel='productImg_1' href='"+imgRootURL+"/"+row.imagePath+"'>" +
				        		"<img src='"+imgRootURL+"/"+row.imagePath+"?x-oss-process=image/resize,h_60/format,png' />" +
				        	"</a>"+
				        "</div>";
			},
			width:"10%"
		},
		{
				field : 'productName',
				title : '商品名称',
				align : 'center',
				width:"35%",
				formatter:function(value, row, index){
					var detail = row;
					var spec_str = "";
					if(detail.productSpecList && detail.productSpecList.length > 0){
						spec_str = "【"
						for(var j = 0 ;j < detail.productSpecList.length; j++){
							var spec = detail.productSpecList[j];
							spec_str += spec.specName+":"+ spec.specValue + "  ";
						}
					}
					if(spec_str != ""){
						spec_str += "】";
					}
					return row.productName+"<br/>" + spec_str;
				}
		},
		{
				field : 'productPrice',
				title : '商品单价',
				align : 'center',
				formatter : function(value, row, index) {
					
					if(row.productPrice != row.productAdjustPrice){
						return "<span style='color:#FC9294;'>调价后:￥"+row.productAdjustPrice+"</span>&nbsp;&nbsp;<span id='productPrice' style='text-decoration:line-through;'>原价：￥"+row.productPrice+"</span>";
					}else{
						return "<span>￥"+row.productPrice+"</span>";
					}
				},
				width:"15%"
		},
		{
				field : 'buyNum',
				title : '购买数量',
				align : 'center',
				formatter : function(value, row, index) {
					return "<span id=\"buyNum\">"+row.buyNum+"</span>";
				},
				width:"10%"
		},
		{
			field : 'productItemMoney',
			title : '金额小计',
			align : 'center',
			formatter : function(value, row, index) {
				return "<span id=\"productItemMoney\">"+row.productItemMoney+"</span>";
			},
			width:"20%"
		}];
			
			
	// 定义查询回调函数（查询参数在此设置）
	var queryParams = function(params) {
	
		var orderCode =  $("#orderCode").val()
		return {
			rows : params.limit, // 页面大小
			page : params.pageNumber, // 页码
			orderCode : orderCode
		};
	};
	
	var url = rootPath + "/orderDetail/listOrderDetailByOrderCode"; // 请求json数据的服务器地址
	sys.initTable('orderProductDetailTable', {
		url : url,
		queryParams : queryParams,
		columns : columns,
		striped : true,
		clickToSelect : true,
		pagination:false,
		onLoadSuccess : function() {
            initFancyBoxImg("productImg_1");
		}
	});
	
	
	
	/**
	 * =============================合同信息==============================
	 */
	
	
	
	
	var url = rootPath +"/orderContract/listOrderContract";
	$.ajax({
        type:"post",
        url:url,
        data:{orderCode:$("#orderCode").val()},
        datatype: "json",
        success:function(json){
        	if(json && json.imageList && json.imageList.length > 0){
        		for(var i = 0 ;i < json.imageList.length ; i++){
        			var image = "<a rel='contractImg_2' href='"+imgRootURL+json.imageList[i]+"?x-oss-process=image/resize,h_1500/format,png'>" +
        							"<img src='"+imgRootURL+json.imageList[i]+"?x-oss-process=image/resize,h_200/format,png' style='width:148px;height:240px;border:1px solid #e8e8e8;margin-left:20px;'/>" +
        						"</a>"
					$("#img_container").append(image);
				}
        		initFancyBoxImg("contractImg_2");
        	}
        	if(json.confirmStatus == '01'){
        		$("#wait_to_confirm_contract").text("1");
        		$("#confirmed_contract").text("0");
        	}else if(json.confirmStatus == '02'){
        		$("#wait_to_confirm_contract").text("0");
        		$("#confirmed_contract").text("1");
        	}
        },
        error: function(){
        	showErr(json.resultMsg);
        }
	});
	
	
	// 确认合同
	$("#btn_confirm_order_contract").click(function(){
		var orderCode = $("#orderCode").val();
		var url = rootPath + "/order/toApproveOrder?orderCode="+orderCode+"&confirmType=1";
		layer.open({
			  type: 2,//弹框类型
			  title: '订单审核',//弹框标题
			  area: ['600px', '425px'],//弹框大小，宽高
			  skin: 'layui-layer-lan',//皮肤
			  fixed: false, //是否固定，不固定
			  content: url,//加载内容，可以是一句话也可以是连接
			  shade:[0.8, '#393D49'],//遮罩，透明度以及颜色
			  cancel: function(index, layero){ 
				  layer.close(index)
				  return false; 
			  }
		});
	});
	
	/**
	 * =================================== 订单付款记录===================
	 */
	
	// 定义列
	var orderContractColumns = [
		{
			field : 'payCode',
			title : '支付流水号',
			align : 'center'
		},
		{
			field : 'payTimeStr',
			title : '支付时间',
			align : 'center'
		},
		{
			field : 'payMoney',
			title : '支付金额 ',
			align : 'center',
			formatter : function(value, row, index) {
				return numberRand2(value);
			}
		},
		{
			field : 'payTypeName',
			title : '支付方式 ',
			align : 'center'
		},
		{
			field : 'bankName',
			title : '支付银行',
			align : 'center'
		},
		{
			field : 'bankAccount',
			title : '支付账号',
			align : 'center'
		},
		{
			field : 'filePath',
			title : '支付凭证',
			align : 'center',
			formatter : function(value, row, index) {
				var file_list_str = "<div class='order_detail_product_image'>";
				if(row.filePath){
					var fileArr = row.filePath.split(",");
					for(var i = 0 ;i < fileArr.length; i++){
						var imgSrc = fileArr[i];
						if(imgSrc && imgSrc.indexOf('u-pro') > -1) {
							imgSrc = imgSrc.split('?')[0];
							file_list_str += "<a rel='contractImg' href='"+imgRootURL+"/"+imgSrc+"?x-oss-process=image/resize,h_1500/format,png'>" +
							"<img src='"+imgRootURL+"/"+imgSrc+"?x-oss-process=image/resize,h_60/format,png' />" +
							"</a>";
						}
					}
				}
				file_list_str += "</div>";
				return file_list_str;
			},
			width:"10%"
		},
		{
				field : 'confirmStatusName',
				title : '确认状态',
				align : 'center'
		},
		{	
			field : '#',
			title : '操作',
			align : 'center',
			formatter : function(value, row, index) {
				var isSalesman = $("#isSalesman").val();
				if(isSalesman == '1'){
					return "";
				}
				if(row.orderStatus == '02' && row.payModel == '01' && row.confirmStatus == '01'){
					return "<a class='btn btn-primary btn-xs' href='javaScript:void(0);' onclick='confirmOrderPay("+ row.id + ",\""+row.orderCode+"\")' style='margin-left:20px;'>确认</a>";
				}else if(row.orderStatus == '08' && row.payModel == '02' && row.approveResult != '02'){
					return "<a class='btn btn-danger btn-xs' href='javaScript:void(0);' onclick='verifyOrderPay("+ row.id + ",\""+row.orderCode+"\")' style='margin-left:20px;'>核销</a>";
				}else{
					return "";
				}
			}
		}];
			
			
	// 定义查询回调函数（查询参数在此设置）
	var orderContractQueryParams = function(params) {
		var orderCode =  $("#orderCode").val()
		return {
			rows : params.limit, // 页面大小
			page : params.pageNumber, // 页码
			orderCode : orderCode
		};
	};
	
	var orderContractUrl = rootPath + "/orderPay/listOrderPay"; // 请求json数据的服务器地址
	sys.initTable('orderPayTable', {
		url : orderContractUrl,
		queryParams : orderContractQueryParams,
		columns : orderContractColumns,
		striped : true,
		clickToSelect : true,
		pagination : false,
		onLoadSuccess : function() {
            initFancyBoxImg("contractImg");
		}
	});
	
	
	/**
	 * =============================== 收发货记录 =============================
	 */
	// 已发货记录
	// 定义列
	var deliveredProductColumns = [
		{
				field : 'no',
				title : '序号',
				align : 'left',
				formatter : function(value, row, index) {
					return index + 1;
				},
				width:"5%"
		},
		{
			field : 'orderCode',
			title : '发货单',
			align : 'center',
			formatter : function(value, row, index) {
				var productDetailBuf = "";
				if(row.deliveredProductList && row.deliveredProductList.length > 0){
					for(var i = 0; i < row.deliveredProductList.length; i ++){
						var detail = row.deliveredProductList[i];
						
						var spec_str = "";
						if(detail.productSpecList && detail.productSpecList.length > 0){
							spec_str = "【"
							for(var j = 0 ;j < detail.productSpecList.length; j++){
								var spec = detail.productSpecList[j];
								spec_str += spec.specName+":"+ spec.specValue + "  ";
							}
						}
						if(spec_str != ""){
							spec_str += "】";
						}
						
						productDetailBuf+="" +
							"<tr>" +
							"	<td style='width:50px;text-align:center;'>" +
							"		<a rel='deliveredProductImg' href='"+imgRootURL+detail.imagePath+"'>" +
							"			<img style='float:left;width:30px;height:30px;border:1px solid #e8e8e8;' src='"+imgRootURL+detail.imagePath+"' onerror='this.src=\""+rootPath+"/statics/images/icon_display.png\"' />" +
							"		</a>" +
							"	</td>" +
							"	<td style='width:350px;border-left:0px solid #fff;'>"+detail.productName+"<br/>"+spec_str+"</td>" +
							"	<td style='width:100px;border-left:0px solid #fff;'>购买总量："+detail.buyNum+"</td>" +
							"	<td style='width:100px;border-left:0px solid #fff;'>已发货数量："+detail.sendNum+"</td>" +
							"</tr>";
					}
				}
				
				return "<div class='order_row'>" +
						"<div class='order_row_info'>" +
							"<div><span class='order_status'><span style='color:red;'>"+(row.signStatus == "01" ? "待签收":"已签收")+"</span></span></div>" +
							"<div class='order_field'><span>【物流信息】</span>" +
							"<span>发货日期："+row.deliveryTimeStr+"</span>" +
							"<span>物流公司："+row.deliveryCompanyName+"</span>" +
							"<span>物流单号："+row.deliveryCode+"</span>" +
							"</div>" +
						"</div>" +
						"<div class='order_separator'></div>"+
						"<div>" +
						"<table class='order_detail_product_table'>" +
						productDetailBuf+
						"</table>" +
						"</div>"
		               "</div>";
			}
		},
		{
			field : '#',
			title : '操作',
			align : 'center',
			formatter : function(value, row, index) {
				var isSalesman = $("#isSalesman").val();
				
				/**
				if(isSalesman == '1'){
					return "";
				}
				*/
				if(row.signStatus == '01'){
					var date = $("#date").val();
					var str = "<div style='margin-top:20px;'>" +
						"<div><button class='btn btn-danger btn-sm' type='button'  onclick='signOrder(\""+row.id+"\",\""+row.orderCode+"\")'>签收</button></div>";
					if ((date - row.deliveryTime) < 86400000) {						
						str += "<div><button class='btn btn-default btn-sm' type='button' style='margin-top:2px;' onclick='modifyDeliverCode(\""+row.id+"\",\""+row.deliveryCompanyName+"\")'>修改运单</button></div>";
					}
					str += "</div>";
					return str;
				}else{
					return "";
				}
			},
			width:"20%"
		}];
			
			
	// 定义查询回调函数（查询参数在此设置）
	var deliveredProductQueryParams = function(params) {
	
		var orderCode =  $("#orderCode").val()
		return {
			rows : params.limit, // 页面大小
			page : params.pageNumber, // 页码
			orderCode : orderCode
		};
	};
	
	var deliveredProductUrl = rootPath + "/orderDeliveredBill/listOrderDetailDelivered"; // 请求json数据的服务器地址
	sys.initTable('orderProductDeliveredTable', {
		url : deliveredProductUrl,
		queryParams : deliveredProductQueryParams,
		columns : deliveredProductColumns,
		striped : true,
		clickToSelect : true,
		pagination:false,
		onLoadSuccess : function() {
            initFancyBoxImg("deliveredProductImg");
		}
	});
	
	// 未发货记录
	var notDeliveredProductColumns = [
			{
				field : 'no',
				title : '序号',
				align : 'left',
				formatter : function(value, row, index) {
					return index + 1;
				},
				width : "5%"
			},
			{
				field : 'imagePath',
				title : '商品图片',
				align : 'center',
				formatter : function(value, row, index) {
					return "<div class='order_detail_product_image'>" + 
								"<a rel='deliveredImg' href='" + imgRootURL + "/"+row.imagePath+"'>" +
									"<img src='" + imgRootURL + "/"+row.imagePath+"?x-oss-process=image/resize,h_60/format,png' />" +
								"</a>" + 
							"</div>";
				},
				width : "10%"
			},
			{
				field : 'productName',
				title : '商品名称',
				align : 'center',
				width : "35%",
				formatter:function(value, row, index){
					var detail = row;
					var spec_str = "";
					if(detail.productSpecList && detail.productSpecList.length > 0){
						spec_str = "【"
						for(var j = 0 ;j < detail.productSpecList.length; j++){
							var spec = detail.productSpecList[j];
							spec_str += spec.specName+":"+ spec.specValue + "  ";
						}
					}
					if(spec_str != ""){
						spec_str += "】";
					}
					return row.productName+"<br/>" + spec_str;
				}
			},
			{
				field : 'buyNum',
				title : '购买数量',
				align : 'center',
				formatter : function(value, row, index) {
					return "<span id=\"buyNum\">" + row.buyNum + "</span>";
				},
				width : "10%"
			},
			{
				field : 'sendNum',
				title : '已发货数量',
				align : 'center',
				formatter : function(value, row, index) {
					return "<span id=\"sendNum\">" + row.sendNum + "</span>";
				},
				width : "10%"
			},
			{
				field : 'sendNum',
				title : '本次发货数量',
				align : 'center',
				formatter : function(value, row, index) {
					var order_status = $("#order_status").val();
					if(order_status == '04'){
						return "<div class='col-md-12 col-sm-12 col-xs-12'>" +
						"<input type='hidden' name='id' value='"+row.id+"'/>" +
						"<input type='text' name='sendNum' class='form-control col-md-6 col-xs-6' style='text-align:center;' value=''>" +
						"</div>";
					}else{
						return "--";
					}
				},
				width : "10%"
			} ];

	// 定义查询回调函数（查询参数在此设置）
	var notDeliveredProductQueryParams = function(params) {

		var orderCode = $("#orderCode").val()
		return {
			rows : params.limit, // 页面大小
			page : params.pageNumber, // 页码
			orderCode : orderCode
		};
	};

	var notDeliveredProductUrl = rootPath + "/orderDetail/listOrderDetailNotDelivered";
	sys.initTable('orderProductNotDeliveredTable', {
		url : notDeliveredProductUrl,
		queryParams : notDeliveredProductQueryParams,
		columns : notDeliveredProductColumns,
		striped : true,
		clickToSelect : true,
		pagination : false,
		onLoadSuccess : function() {
            initFancyBoxImg("deliveredImg");
		}
	});
	
	
	// 部分发货
	$("#btn_confirm_send").click(function(){
		var url = rootPath + "/orderDeliveredBill/sendPartOrder";
		var ids = [];
		var sendNum = [];
		var detailIds = [];
		
		$("input[name='id']").each(function(i,item){
			ids.push($(this).val());
		});
		var tmp_send_num = 0;
		$("input[name='sendNum']").each(function(i,item){
			if($(this).val() == "" || $(this).val() == undefined || $(this).val() == null){
				sendNum.push(0);
				tmp_send_num = tmp_send_num + 0;
			}else{
				sendNum.push($(this).val());
				tmp_send_num = tmp_send_num + parseInt($(this).val());
			}
		});
		var timeout = 1000;
		if (tmp_send_num == 0) {
			layer.msg('请填写发货数量',{time:timeout});
			return false;
		}
		setTimeout(function(){
			$("#btn_confirm_send").show();
			var data = $("#orderProductNotDeliveredTable").bootstrapTable("getData");
			for(var i = 0 ;i < data.length; i++){
				var row = data[i];
				detailIds.push(row.id);
				if((parseInt(sendNum[i])+parseInt(row.sendNum)) > parseInt(row.buyNum)){
					layer.alert('发货数量不能超过购买数量',{icon: 6});
					return false;
				}
			}
			var url = rootPath + '/order/toSendPartOrder?orderCode='+$("#orderCode").val()+"&ids="+ids+"&sendNum="+sendNum+"&detailIds="+detailIds;
			layer.open({
				  type: 2,//弹框类型
				  title: '订单(部分)发货',//弹框标题
				  area: ['750px', '470px'],//弹框大小，宽高
				  skin: 'layui-layer-lan',//皮肤
				  fixed: false, //是否固定，不固定
				  content: url,//加载内容，可以是一句话也可以是连接
				  shade:[0.8, '#393D49'],//遮罩，透明度以及颜色
				  cancel: function(index, layero){ 
					  layer.close(index)
					  return false; 
				  }
			});
		}, timeout);
	
	});
	
	/**
	 * ======================================== 订单日志 ==============================================
	 */
	
	// 定义列
	var orderLogColumns = [
		{
			field : 'no',
			title : '序号',
			align : 'left',
			formatter : function(value, row, index) {
				return index + 1;
			}
		},
		{
			field : 'opTimeStr',
			title : '时间 ',
			align : 'center'
		},
		{
			field : 'logContent',
			title : '操作日志',
			align : 'center'
		},
		{
			field : 'operaterName',
			title : '操作人',
			align : 'center'
		}];
			
			
	// 定义查询回调函数（查询参数在此设置）
	var orderLogQueryParams = function(params) {
	
		var orderCode =  $("#orderCode").val()
		return {
			rows : params.limit, // 页面大小
			page : params.pageNumber, // 页码
			orderCode : orderCode
		};
	};
	
	var orderLogUrl = rootPath + "/orderLog/listOrderLogPage"; // 请求json数据的服务器地址
	sys.initTable('orderLogTable', {
		url : orderLogUrl,
		queryParams : orderLogQueryParams,
		columns : orderLogColumns,
		striped : true,
		clickToSelect : true,
		pagination : false
	});
	
	
});

// 订单付款确认操作
function confirmOrderPay(id,orderCode){
	var url = rootPath + "/order/toApproveOrder?orderCode="+orderCode+"&confirmType=2";
	layer.open({
		  type: 2,//弹框类型
		  title: '订单审核',//弹框标题
		  area: ['600px', '425px'],//弹框大小，宽高
		  skin: 'layui-layer-lan',//皮肤
		  fixed: false, //是否固定，不固定
		  content: url,//加载内容，可以是一句话也可以是连接
		  shade:[0.8, '#393D49'],//遮罩，透明度以及颜色
		  cancel: function(index, layero){ 
			  layer.close(index)
			  return false; 
		  }
	});
}

//订单付款核销操作
function verifyOrderPay(id, orderCode) {
	var url = rootPath + "/order/toVerifyOrder?orderCode="+orderCode+"&confirmType=2";
	layer.open({
		  type: 2,//弹框类型
		  title: '订单核销',//弹框标题
		  area: ['600px', '425px'],//弹框大小，宽高
		  skin: 'layui-layer-lan',//皮肤
		  fixed: false, //是否固定，不固定
		  content: url,//加载内容，可以是一句话也可以是连接
		  shade:[0.8, '#393D49'],//遮罩，透明度以及颜色
		  cancel: function(index, layero){ 
			  layer.close(index)
			  return false; 
		  }
	});
}


//签收物流单
function signOrder(bill_id, order_code){
	var url = rootPath + "/order/confirmSign";
	$.ajax({
		type: 'POST',
		url: url,
		async: true,
		data: {
			deliveryBillId:bill_id,
			orderCode:order_code
		},
		dataType: 'json',
		success: function(json) {
			if(json && json.resultCode == '1'){
				layer.msg('签收成功',{time:1000});
				setTimeout(function(){
					window.location.href=rootPath+"/order/toOrderDetail?orderCode="+order_code+"&tabIndex=4";
				},1000);
			}
		},
		error:function(){
		}
	})
}

/**
 * 打开弹出层
 * @Description do-something
 * @author xu_cc
 * @date 创建时间：2018年2月24日 下午3:03:31
 * @param orderCode
 */
function openCancelWin(orderCode) {
	$("#cancelOrderCode").val(orderCode);
	$("#cancelIntro").val($("#cancelReasonCombo option:selected").text());
	$("#cancelModal").modal('show');
}

//取消订单
function doCancelOrder(){
	var url = rootPath + "/order/cancelOrder";
	var orderCode = $("#cancelOrderCode").val();
	var cancelReason = $("#cancelReasonCombo option:selected").text();
	var cancelIntro = $("#cancelIntro").val();
	if(orderCode) {
		var params = {
				orderCode : orderCode,
				cancelReason: cancelReason,
				cancelIntro : cancelIntro
		};
		
		$.ajax({
			type:"post",
			url:url,
			data:params,
			datatype: "json",
			success:function(json){
				$("#cancelModal").modal('hide');
				if(json.resultCode == '1') {
					layer.alert('取消成功', { icon: 6});
					setTimeout(function(){
						window.location.href=rootPath+"/order/toOrderDetail?orderCode="+orderCode+"&tabIndex=1";
					},1000);
				} else {
					showMsg(json.resultMsg);
				}
			},
			error: function(){
				sys.showErr("取消失败");
			}
		});
	} else {
		sys.showErr("取消失败！");
	}
}

//弹窗修改快递单号
function modifyDeliverCode(id, deliveryCompanyName){
	var url = rootPath + "/orderDeliveredBill/toModifyDeliverCodeForm?id="+id;
	layer.open({
		  type: 2,//弹框类型
		  title: '修改运单号',//弹框标题
		  area: ['580px', '290px'],//弹框大小，宽高
		  skin: 'layui-layer-lan',//皮肤
		  fixed: false, //是否固定，不固定
		  content: url,//加载内容，可以是一句话也可以是连接
		  shade:[0.8, '#393D49'],//遮罩，透明度以及颜色
		  cancel: function(index, layero){ 
			  console.log(index);
			  layer.close(index)
			  return false; 
		  }
	});
}
